package com.ysh.smartplatform.websocket;

import com.ysh.smartplatform.event.DevicePowerEvent;
import org.springframework.context.annotation.Lazy;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 袁胜虎 on 2022/9/14 22:31
 */
@Component
@Lazy(false)
public abstract class MyBaseWebSocketHandler extends TextWebSocketHandler {
    Logger logger = LoggerFactory.getLogger(this.getClass());


    //用于保存所有会话的集合,key 是唯一表示, value 是会话
    private Map<String, WebSocketSession> allClients = new ConcurrentHashMap<>();
    //key是设备的id,value是最后链接的时间
    private ConcurrentHashMap<String,Long> updateTimes = new ConcurrentHashMap<>();
    //保留设备最后的会话时间
    @Autowired
    private ApplicationContext context;

    /**
     * 当客户端和服务端建立连接的时候,就相当于你登录 QQ 成功,服务器必须保存你的会话数据,不然给你发送数据的时候就找不到你了,每个建立连接的都需要保存
     *
     * @param session 当前正在会话的人
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception{
       String path = session.getUri().getPath();
       String deviceId = path.substring(path.lastIndexOf("/")+1);
       session.getAttributes().put("deviceId",deviceId);
       updateTimes.put(deviceId,System.currentTimeMillis());
       if (isNeedUpdateStatus()){
//           logger.error("{}更新设备{}在线信息", getClass().getName(), deviceId);
           context.publishEvent(DevicePowerEvent.sendOpen(deviceId));
       }
        //如果当前客户端之前连接过,则先关闭并且移除
        WebSocketSession socketSession = allClients.get(deviceId);
        try {
            if (socketSession != null) {
                allClients.remove(deviceId);
                if (socketSession.isOpen()) {
                    socketSession.close();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        allClients.put(deviceId, session);//根据之前拦截保存的唯一表示来保存会话
    }


    public abstract boolean isNeedUpdateStatus();
}
